import {Component, OnInit, ViewChild} from '@angular/core';
import {Clipboard} from '@angular/cdk/clipboard';
import {NzMessageService} from 'ng-zorro-antd/message';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute} from '@angular/router';
import { NzModalService } from 'ng-zorro-antd/modal';

import {defalutImg} from 'src/app/comm';
import {UsedStoreZservice} from '../../used-store-zservice';
import {PermissionService} from '../../../../service/permission.service';
import { HomeComponent } from '../../../home/home.component';
import { SecondDescentService } from '../../used-marketing-manage/services/second-descent.service';

@Component({
  selector: 'app-used-order-details',
  templateUrl: './used-order-details.component.html',
  styleUrls: ['./used-order-details.component.scss']
})
export class UsedOrderDetailsComponent implements OnInit {
  @ViewChild('followUpRef') followUpRef: any;

  routerParams: any = {};
  fallback: string = defalutImg;
  cardSize: any = 'default';
  deadline = 1637738945000 + 1000 * 60 * 10;

  orderDetails: any = {};
  goodsTableData: any = [];
  saleTableData: any = [];
  orderAllInfos: any = {};

  // 物流
  selectedIndex: number = 0;
  orderExpressList: any = [];
  logisticsList: any = [];

  // 售后退款Modal
  isAfterSaleVisible: boolean = false;
  afterSaleForm!: FormGroup;
  isRefundVisible: boolean = false;
  confirmText: string = '';

  // 跟进 Modal
  initParams: any = {
    type: 1, // type  1、订单 2、售后 3、客户 4、出库 5、直降 6、退税 7、机器 8、商品
    modelId: 2, // 类型 1、旧的表示二手回收 2、表示二手商城 3、表示二手回收
    relationInformation: ''
  };

  childTableData: any = []; // 子订单

  // 旧机信息status
  oldOrderOptions = [
    {value: 0, label: '待生成'},
    {value: 1, label: '待打款'},
    {value: 2, label: '打款完成'},
    {value: 3, label: '打款失败'}
  ];
  // 补贴规则options
  subsidyRuleList: Array<any> = [];

  constructor(
    private homeComponent: HomeComponent,
    private clipboard: Clipboard,
    private fb: FormBuilder,
    private activatedRoute: ActivatedRoute,
    private services: UsedStoreZservice,
    private message: NzMessageService,
    private modal: NzModalService,
    public permissionService: PermissionService,
    private secondDescentService: SecondDescentService
  ) {
    activatedRoute.queryParams.subscribe((res: any) => {
      this.routerParams = res || {};
    });
  }

  ngOnInit(): void {
    this.homeComponent.scrollTopZero();
    // 售后退款
    this.afterSaleForm = this.fb.group({
      refundPrice: ['', [Validators.required]],
    });

    this.loadSubsidyRuleData();
    this.loadDetailsData();
  }

  // 查询补贴规则
  async loadSubsidyRuleData() {
    const res: any = await this.services.getSubsidyRuleData('es_swap_list');
    this.subsidyRuleList = res.data.content ? JSON.parse(res.data.content) : [];
  }

  async loadDetailsData() {
    let params = {
      id: this.routerParams.id
    };
    const msgId = this.message.loading('数据加载中..', { nzDuration: 0 }).messageId;
    const res: any = await this.services.queryMallOrderDetails(params);
    this.message.remove(msgId);
    
    if (res.code === 0) {
      this.orderAllInfos = res.data || {};
      // order：详情，orderExpress：物流，orderRefunds：售后
      const {order, orderExpress, orderRefunds, oldList} = res.data || {};
      this.orderDetails = order || {};
      this.orderExpressList = orderExpress || []; // 快递
      this.logisticsList = this.parseArry(orderExpress[0]?.expressTraces); // 物流详情

      this.goodsTableData = order.mallOrderDetailsList || []; // 商品信息
      this.saleTableData = orderRefunds || []; // 售后

      this.childTableData = oldList || []; // 子订单
    } else {
      this.message.error(res.message);
    }
  }

  // tabChange
  tabChange(index: number) {
    this.logisticsList = this.parseArry(this.orderExpressList[index]?.expressTraces);
  }

  // 拷贝
  copy(copyStr: string) {
    this.clipboard.copy(copyStr);
    this.message.success('已成功复制到剪切板');
  }

  showModal() {
    this.afterSaleForm.reset();
    this.isAfterSaleVisible = true;
  }

  handleCancel() {
    this.isAfterSaleVisible = false;
  }

  submitForm() {
    if (this.afterSaleForm.valid) {
      this.confirmText = '';
      this.isRefundVisible = true;
    } else {
      Object.values(this.afterSaleForm.controls).forEach(control => {
        if (control.invalid) {
          control.markAsDirty();
          control.updateValueAndValidity({onlySelf: true});
        }
      });
    }
  }

  // 确认退款
  refundCancel() {
    this.isRefundVisible = false;
  }

  async refundConfirm() {
    if (!this.confirmText || this.confirmText !== '确认退款') {
      this.message.warning('请输入"确认退款"');
      return;
    }
    let params = {
      id: this.routerParams.id,
      ...this.afterSaleForm.value
    };
    
    const res: any = await this.services.refundSalesData(params);
    if (res.code == 0) {
      this.message.success('操作成功');
      this.loadDetailsData();
      this.isRefundVisible = false;
      this.isAfterSaleVisible = false;
    } else {
      this.message.error(res.message);
    }
  }

  // 跟进
  followModal(orderNum: any) {
    this.initParams.relationInformation = orderNum || '';
    this.followUpRef.isModelVisible = true;
  }

  // 商品信息合计
  totalReduceNum(key: string) {
    let tempNum = 0;
    if (this.goodsTableData.length) {
      tempNum = this.goodsTableData.reduce((total: any, item: any) => {
        return total + (item[key] || 0);
      }, 0);
    }
    return tempNum || 0;
  }

  // 商品信息退货量合计
  totalReturnNum(key: string) {
    let returnNum: any = [];
    returnNum = this.goodsTableData.filter((item: any) => item[key] > 0);
    
    return returnNum?.length || 0;
  }

  // 统计合计
  reduceNum(array: any[], str: string) {
    let tempNum = 0;
    if (array.length) {
      tempNum = array.reduce((total, item) => {
        return total + (item[str] || 0);
      }, 0);
    }
    return tempNum || 0;
  }

  back() {
    history.back();
    JSON.parse;
  }

  parseArry(arr: string) {
    return arr ? JSON.parse(arr) : [];
  }

  // 倒计时(下单后 xx 过期)
  countDownNum() {
    let ctTime = new Date(this.orderDetails.createTime).getTime(); // 创建时间
    let ovTime = new Date(this.orderDetails.payOverTime).getTime(); // 过期时间

    if (this.orderDetails.status == 2 && this.orderDetails.payOverTime && (ovTime - ctTime) > 0) {
      return ctTime + (ovTime - ctTime);
    } else {
      return 0;
    }
  }

  // 旧机status filter
  oldOrderStatusFilter(status: number | string) {
    let tempObj: any = this.oldOrderOptions.find(item => item.value == status);
    return tempObj?.label || '-';
  }

  // 客服取消订单
  kfCancelOrder() {
    this.modal.confirm({
      nzTitle: '取消订单',
      nzContent: '<b style="color: red;">确认取消？该操作不可逆，请提前和用户沟通</b>',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        let messId = this.message.loading('订单取消中..', { nzDuration: 0 }).messageId;
        try {
          const res: any = await this.secondDescentService.cancelOrderData({ orderId: this.orderDetails.id, status: 11 });
          this.message.remove(messId);

          if (res.code == 0) {
            this.message.success('订单取消成功');
            this.loadDetailsData()
          } else {
            this.message.error(res.message || '订单取消失败');
          }
        } catch (error: any) {
          this.message.remove(messId);
          this.message.error(error);
        }
      },
      nzCancelText: '取消'
    })
  }
}
